import BTComposite from "../../Base/BTComposite";
import { NodeStatues } from "../../Enum";

export default class CompositeRandomSequence extends BTComposite {

    executeOrder: Array<number> = [];
    public onstart(): void {
        super.onstart();
        this.shuffle()

    }

    public canExecute(): boolean {
        return this.executeOrder.length && this.statues !== NodeStatues.Failed;
    }

    public onChildExecute(Statue: NodeStatues): void {
        switch (Statue) {
            case NodeStatues.Success:
                this.executeOrder.pop();
                if (this.executeOrder.length) {
                    this.statues = NodeStatues.Success;
                } else {
                    this.statues = NodeStatues.Running
                }
                break;
            case NodeStatues.Failed:
                this.statues = NodeStatues.Failed;
                break;
            case NodeStatues.Running:
                this.statues = NodeStatues.Running;
                break;
            default:
                break;
        }
    }
    public getIndex(): number {
        return this.executeOrder[this.executeOrder.length - 1];
    }
    shuffle() {
        const indexList = Array.from({ length: this.children.length }, (_, i) => i);
        for (let i = indexList.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (indexList.length));
            this.executeOrder.push(indexList.splice(j, 1)[0]);
        }
    }
    // public onUpdate(): NodeStatues {
    //     if (this.statues == NodeStatues.Failed) {
    //         return NodeStatues.Failed;
    //     }
    //     if (!this.executeOrder.length) {
    //         return NodeStatues.Failed;
            
    //     }
    
    //     const child = this.children[this.getIndex()];
    //     console.log("执行顺序", `${this.getIndex()}`);
    //     const res = child.run();
    //     if (res === NodeStatues.Failed) {
    //         this.statues = NodeStatues.Failed;
    //         return NodeStatues.Failed;

    //     }

    //     if (res === NodeStatues.Success) {
    //         this.executeOrder.pop();
    //     }
    //     return NodeStatues.Running;
    // }
}